<template>
  <base-modal
    class="service-dialog-container"
    :title="$t('common.form.preview.serviceItem.title2')"
    :show.sync="visible"
    width="700px"
  >
    <el-table
      ref="multipleTable"
      header-row-class-name="base-table-header-v3"
      row-class-name="base-table-row-v3"
      @select="handleSelection"
      @select-all="handleSelection"
      :data="data"
      v-loading="listLoading"
      border>
      <el-table-column
        type="selection"
        align="center"
        width="40"
        v-if="columns && columns.length"
      ></el-table-column>
      <el-table-column
        v-for="(column, index) in columns"
        :key="`${column.fieldName}_${index}`"
        :label="column.displayName"
        :prop="column.fieldName"
        show-overflow-tooltip
        :min-width="column.minWidth">
        <template slot-scope="scope">
          <!-- 结算规则 S -->
          <template v-if="column.fieldName === 'settlementRules'">
            <el-select v-model="scope.row.settlementRulesId" :placeholder="$t('zhongqi.tipList.tips1')" @change="handleChangeRule(scope.row)">
              <el-option
                v-for="item in ruleOptions"
                :key="item.value"
                :label="item.ruleName"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
          <!-- 结算规则 E -->

          <!-- 单价 S -->
          <template v-else-if="column.fieldName === 'salePrice'">
            {{ scope.row | fmt_salePrice_currency }}
          </template>
          <!-- 单价 E -->
          <!-- 小计 S -->
          <template v-else-if="column.fieldName === 'total'">
            {{ scope.row | fmt_total_currency}}
          </template>
          <!-- 小计 E -->
          <template v-else>{{ scope.row[column.fieldName] }}</template>
        </template>
      </el-table-column>
    </el-table>

    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="submit">{{$t('common.base.submit')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
/* util */
import * as _ from 'lodash';
import * as math from 'mathjs';
/* model */
import { PART_SERVICE_LIST_PRENUM_MAX_LENGTH } from '@src/model/const/Number';

import TaskReceiptMixin from '@src/component/form/mixin/taskReceipt';
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()
export default {
  name: 'service-list-dialog',
  mixins: [TaskReceiptMixin],
  props: {
    fields: {
      type: Array,
      default: () => ([])
    },
    data: {
      type: Array,
      default: () => ([])
    },
    value: {
      type: Array,
      default: () => ([])
    },
    // 结算规则下拉数据
    ruleOptions: {
      type: Array,
      default: () => ([])
    },
    // 工单结算规则灰度
    isShowSettlementRules: {
      type: Boolean,
      default: false
    },
    taskId: {
      type: String,
      default: ''
    },
    onlyFromServiceItem: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      visible: false,
      multipleSelection: [],
      isNotOnServiceList: [],
      listLoading: false
    }
  },
  computed: {
    columns() {
      let list = this.fields.filter(field => field.enabled && !field.isHidden);

      if(this.isShowSettlementRules) {
        list.splice(2, 0, {
          displayName: this.$t('common.zhongqi.title1'),
          fieldName: 'settlementRules',
          minWidth: '110px',
        })
      }

      return list;
    }
  },
  methods: {
    /**
    * @description 打开添加服务项目弹窗
    */
    open() {
      // 勾选已选择
      this.multipleSelection = _.cloneDeep(this.value);
      this.matchSelected();

      // 过滤出非清单中的服务项目
      this.isNotOnServiceList = this.multipleSelection.filter(ms =>
        this.data.every(c => c.id !== ms.id)
      )

      this.visible = true;
    },
    /**
    * @description 勾选列表数据
    */
    handleSelection(selection) {
      this.multipleSelection = _.uniqWith([...this.isNotOnServiceList, ...selection], _.isEqual);
    },
    // 把选中的数据匹配出来
    matchSelected() {
      this.$refs.multipleTable.clearSelection();

      const selected = this.data.filter(c => {
        if (this.multipleSelection.some(sc => sc.id === c.id)) {
          this.multipleSelection = this.multipleSelection.filter(
            sc => sc.id !== c.id
          );
          this.multipleSelection.push(c);
          return c;
        }
      }) || [];

      selected.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(row, true);
      })
    },
    /**
    * @description 提交
    */
    async submit() {
      let selected = this.multipleSelection.length - this.isNotOnServiceList.length;
      if (!selected) return this.$platform.alert(this.$t('common.form.tip.serviceItem.tips1'));

      // 去重
      let serviceData = [...this.value];
      this.multipleSelection.forEach(item => {
        let idx = this.value.findIndex(val => val.id == item.id && val.salePrice == item.salePrice);
        // 不存在
        if (idx == -1) serviceData.push(_.cloneDeep(item));
        // 存在时合并数量
        if (idx > -1) {
          serviceData[idx].number = this.onlyFromServiceItem ? Number(item.number) : Number(math.add(math.bignumber(this.value[idx].number), item.number))
          if (serviceData[idx].number > PART_SERVICE_LIST_PRENUM_MAX_LENGTH) serviceData[idx].number = PART_SERVICE_LIST_PRENUM_MAX_LENGTH
          serviceData.splice(idx, 1, serviceData[idx])
        }
      })
      if(internationalGray) {
        let exchangeRateObj = await this.getCurrenyKeyArr(serviceData, this.totalCurrency)
        serviceData = serviceData.map(item => {
          let salePriceCurrency = item.salePriceCurrency ? item.salePriceCurrency : 'CNY'
          if(!item.exchangeMethod) {
            item.exchangeMethod = 1;
            item.exchangeRate = exchangeRateObj[salePriceCurrency];
          }
          return item
        })
      }
      if(this.isShowSettlementRules) {
        const isPass = this.multipleSelection.some(item => item?.settlementRulesId?.toString().length <= 0)
        if(isPass) {
          return this.$message.warning(this.$t('zhongqi.tipList.tips2'))
        }
      }

      this.$emit('submit', serviceData);

      this.visible = false;
    },
    // change 规则
    handleChangeRule(row) {
      let selectRuleArr = this.ruleOptions.filter(item => {
        return item.id == row.settlementRulesId
      })
      
      row.isFree = selectRuleArr[0].attribute.isFree;
      row.isFreeName = selectRuleArr[0].attribute.isFreeName;
      row.settlementRules = selectRuleArr[0].ruleName;
      row.qualityStatus = selectRuleArr[0].attribute.qualityStatus; 
    }
  }
}
</script>

<style lang="scss" scoped>
.service-dialog-container {
  ::v-deep .base-modal-body {
    padding: 16px 24px;
  }

  .el-table {
    ::v-deep .el-checkbox {
      width: auto;
      line-height: 40px;
      margin-bottom: 0;
      padding: 0;
    }

    ::v-deep .el-table-column--selection {
      .cell {
        padding-right: 10px !important;
      }
    }
  }
}
</style>